package com.sdw.message.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SecurityFilter implements Filter{

	private final static Log log = LogFactory.getLog(SecurityFilter.class);
    private String _redirectUrl;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this._redirectUrl = filterConfig.getInitParameter("redirectUrlIfUnLogin");
    }

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain chain) throws IOException, ServletException {
		final HttpServletRequest request = (HttpServletRequest)servletRequest;
        final HttpServletResponse response = (HttpServletResponse)servletResponse;

        final HttpSession session = ((HttpServletRequest)request).getSession();
		
        Object userName = session.getAttribute("userName");
        if(userName == null){
        	String requestURI = request.getRequestURI();
        	if(!requestURI.contains("login.jsp")){
        		log.info("find exception enter site:" + request.getRequestURI());
        		response.sendRedirect(request.getContextPath() + this._redirectUrl);
        		return;
        	}
        }
        
        chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
}
